package com.drcoffee.drcoffeemall.util;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import com.drcoffee.drcoffeemall.entry.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/*
 * aliyun OSS对象存储
 * */
@Slf4j
@Component
public class OSSUtil {

    @Value("${oss_config.accessKeyId}")
    private String accessKeyId;

    @Value("${oss_config.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss_config.endpoint}")
    private String endpoint;

    @Value("${oss_config.bucketName}")
    private String bucketName;

    /*
     * 上传文件
     * */
    public Result upload(MultipartFile file, String file_path, String file_name) {
        OSS ossClient = null;
        try {
            // 检查文件大小
            long maxSize = 5 * 1024 * 1024; // 5MB
            if (file.getSize() > maxSize) {
                // 文件大小不能超过2MB
                return new Result(2, "SUCCESS", "The file size cannot exceed 5MB", null);
            }

            // 获取当前时间戳
            long timestamp = System.currentTimeMillis();

            // 格式化时间戳为字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String formattedTimestamp = sdf.format(new Date(timestamp));

            // 图片文件名
            file_name = formattedTimestamp + "_" + UUID.randomUUID() + "_" + file_name;
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
            ossClient.putObject(bucketName, file_path + file_name, new ByteArrayInputStream(file.getBytes()));
            return new Result(1, "SUCCESS", "", file_name);
        } catch (Exception e) {
            log.error("===================== upload()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /*
     * 上传文件
     * */
    public Result uploadFileList(MultipartFile[] files, String file_path) {
        List<Result> results = new ArrayList<>();
        OSS ossClient = null;
        try {
            for (MultipartFile file : files) {
                if (file.getSize() > 5 * 1024 * 1024) {
                    // 文件大小不能超过5MB
                    results.add(new Result(2, "ERROR", "The file size of " + file.getOriginalFilename() + " exceeds 5MB.", null));
                    continue;
                }

                // 文件类型检查，这里仅检查图像类型
                String contentType = file.getContentType();
                if (!contentType.startsWith("image/")) {
                    results.add(new Result(2, "ERROR", "Only image files are allowed for " + file.getOriginalFilename(), null));
                    continue;
                }

                // 获取当前时间戳
                long timestamp = System.currentTimeMillis();

                // 格式化时间戳为字符串
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String formattedTimestamp = sdf.format(new Date(timestamp));

                // 图片文件名，添加随机字符串以避免文件名冲突
                String file_name = formattedTimestamp + "_" + UUID.randomUUID() + "_" + file.getOriginalFilename();

                CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
                ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
                ossClient.putObject(bucketName, file_path + file_name, new ByteArrayInputStream(file.getBytes()));

                results.add(new Result(1, "SUCCESS", "File uploaded successfully: " + file_name, file_name));
            }

            return new Result(1, "SUCCESS", " ", results);
        } catch (OSSException | ClientException e) {
            log.error("===================== uploadFileList()异常： =====================", e);
            return new Result(-1, "ERROR", "Error during file upload: " + e.getMessage(), null);
        } catch (Exception e) {
            log.error("===================== uploadFileList()异常： =====================", e);
            return new Result(-1, "ERROR", "Unknown error: " + e.getMessage(), null);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    /*
     * 下载文件
     * */
    public Object download(String file_path) {
        System.out.println(file_path);
        OSS ossClient = null;
        try {
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, file_path);
            System.out.println(ossObject);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Length", String.valueOf(ossObject.getObjectMetadata().getContentLength()));
            headers.add("Content-Type", ossObject.getObjectMetadata().getContentType());

            // 读取文件内容到字节数组
            InputStream inputStream = ossObject.getObjectContent();
            byte[] fileBytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            // 返回ResponseEntity对象
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileBytes);
        } catch (Exception e) {
            log.error("===================== download()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /*
     * 删除文件
     * */
    public Object deleteFile(String file_path) {
        OSS ossClient = null;
        try {
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
            ossClient.deleteObject(bucketName, file_path);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== deleteFile()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static void main(String[] args) {

        String accessKeyId ="LTAI5t93UGXDqyiWDdAGAbfw";


        String accessKeySecret="l3uTcGlGqZ310P91HaWMBO7p4DhYgm";


         String endpoint="https://oss-accelerate.aliyuncs.com";


         String bucketName="dmall-dr-coffee";

        String objectName = "tishi.txt";

        String localFilePath = "C:/Users/wangz/Desktop/tishi.txt";

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


        ossClient.putObject(bucketName, objectName, new File(localFilePath));

        // 关闭OSSClient
        ossClient.shutdown();
    }


}
